import urwid
import urwid.curses_display
import twitter
__version__ = '0.1.h'

login = 'yourusername'
password = 'yourpassword'

class Tweet(urwid.Text):
        def __init__(self, username, *args):
            urwid.Text.__init__(self, *args)
            self.username = username

        def selectable(self):
            return True

        def keypress(self, size, key):
            return key

class Twikke(object):
	def __init__(self, login, password):
                #connect to Twitter
                self.connection = twitter.Api(login, password)
		self.items = urwid.SimpleListWalker(self.getTimeline())
		self.listbox = urwid.ListBox(self.items)
		instruct = urwid.Text("F2-Timeline | F3-Atualizar | F4-Postar | F5-Amigos | F6-Seguidores | F8-Sair")
		header = urwid.AttrWrap( instruct, 'header' )
		self.top = urwid.Frame(self.listbox, header)

        def getTimeline(self):
               timeline = [] 
               for tweet in self.connection.GetFriendsTimeline():
                  timeline.append(Tweet( tweet.user.screen_name, "%s (%s) %s:\n %s\n" % (tweet.user.name.encode('utf-8'), tweet.user.screen_name.encode('utf-8'), tweet.relative_created_at, tweet.text.encode('utf-8'))))
                  timeline.append(urwid.Divider("-"))
               return [ urwid.AttrWrap( urwid.Text("Timeline"), 'title' ) ] + [ urwid.AttrWrap( tweet, None, 'selected' ) for tweet in timeline ]

        def getFriends(self):
               friendlist = []
               for friend in self.connection.GetFriends():
                   friendlist.append(Tweet( friend.screen_name, "%s (%s)" % (friend.name.encode('utf-8'), friend.screen_name.encode('utf-8'))))
               return [ urwid.AttrWrap( urwid.Text("Friends"), 'title' ) ] + [ urwid.AttrWrap( friend, None, 'selected' ) for friend in friendlist ]

        def getFollowers(self):
               followerlist = []
               for follower in self.connection.GetFollowers():
                   followerlist.append(Tweet( follower.screen_name, "%s (%s)" % (follower.name.encode('utf-8'), follower.screen_name.encode('utf-8'))))
               return [ urwid.AttrWrap( urwid.Text("Followers"), 'title' ) ] + [ urwid.AttrWrap( follower, None, 'selected' ) for follower in followerlist ]

	def main(self):
		self.ui = urwid.curses_display.Screen()
		self.ui.register_palette([
			('header', 'light red', 'black', 'standout'),
                        ('selected', 'dark green', 'black', 'standout'),
                        ('title', 'yellow', 'black', 'standout'),
			])
		self.ui.run_wrapper( self.run )
	
	def run(self):
		size = self.ui.get_cols_rows()

		while True:
			self.draw_screen( size )
			keys = self.ui.get_input()

                        if "f2" in keys or "f3" in keys:
                                self.items[:] = urwid.SimpleListWalker(self.getTimeline())
                                
                        if "f4" in keys:
				self.items[:] = urwid.SimpleListWalker([urwid.Edit(('title','mensagem:'))])
                       
                        if "enter" in keys:
                                try:
                                    if self.items[0].edit_text:
                                       self.connection.PostUpdate( self.items[0].edit_text.decode('utf-8') )
                                       self.items[:] = urwid.SimpleListWalker( [ urwid.Text( 'twitado!' ) ] )
                                except:
                                    #print 'erro!'
                                    #pass
                                    try:
                                        user_to_reply = self.listbox.get_focus()[0].username
                                        self.items[:] = urwid.SimpleListWalker( [ urwid.Edit( ( 'title' , 'mensagem: ' ) ) ] )
                                        self.items[0].insert_text( '@%s '% (user_to_reply) )
                                    except:
                                        pass


                        if "f5" in keys:
                                 self.items[:] = urwid.SimpleListWalker(self.getFriends())
                                 
                        if "f6" in keys:
                                 self.items[:] = urwid.SimpleListWalker(self.getFollowers())

                        if "f8" in keys:
                                break

			for k in keys:
				if k == "window resize":
					size = self.ui.get_cols_rows()
					continue
				self.listbox.keypress( size, k )
	
	def draw_screen(self, size):
		canvas = self.top.render( size, focus=True )
		self.ui.draw_screen( size, canvas )

Twikke(login, password).main()
